package com.itita.ww2.utils;

import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itita.ww2.core.ServerService;

/**
 * MyBatis Session Util
 * 管理Session(支持多线程)
 * @author NorthLan 
 *
 */
public class MyBatisSessionUtil {
	private static final Logger logger = LoggerFactory.getLogger(MyBatisSessionUtil.class);
	private static MyBatisSessionUtil instance = new MyBatisSessionUtil();

	public static MyBatisSessionUtil getInstance() {
		return instance;
	}

	private SqlSessionFactory m_SqlSessionFactory = null;
	private Lock lock; // 锁

	public MyBatisSessionUtil() {
		this.lock = new ReentrantLock();
	}

	@org.junit.Test
	public void init() {
		if (this.m_SqlSessionFactory != null) {
			return;
		}
		try {
			ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
			ClassLoader extensionLoader = getClass().getClassLoader();
			Thread.currentThread().setContextClassLoader(extensionLoader);
			// 
			InputStream in = Resources.getResourceAsStream("resources/mybatis-config.xml"); // 获取包内的文件
			Properties properties = ServerService.getInstance().getConfigProperties();
			//			Properties testProperties = new Properties();
			//			testProperties.load(Resources.getResourceAsStream("resources/config.properties"));
			m_SqlSessionFactory = new SqlSessionFactoryBuilder().build(in, properties);
			//
			Thread.currentThread().setContextClassLoader(origLoader);
			logger.info("[MyBatis] is ready!");
			//			System.out.println("[MyBatis] is ready!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private SqlSessionFactory getSqlSessionFactory() {
		if (this.m_SqlSessionFactory == null) {
			this.lock.lock();
			try {
				init();
			} finally {
				this.lock.unlock();
			}
		}
		return this.m_SqlSessionFactory;
	}

	/**
	 * SqlSession (单)
	 */
	public SqlSession getSession() {
		return getSqlSessionFactory().openSession();
	}

	/**
	 * 批量执行的SqlSession
	 */
	public SqlSession getBatchSession() {
		return getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
	}
}
